package com.ltmonitor.web.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.ltmonitor.entity.Department;
import com.ltmonitor.entity.DriverInfo;
import com.ltmonitor.entity.Terminal;
import com.ltmonitor.entity.VehicleData;
import com.ltmonitor.entity.VehicleInfoModifyRecord;
import com.ltmonitor.service.IDepartmentService;
import com.ltmonitor.service.IDriverInfoService;
import com.ltmonitor.service.IRealDataService;
import com.ltmonitor.service.ITerminalService;
import com.ltmonitor.web.util.JsonMessage;
import com.ltmonitor.web.util.OnlineUser;
import com.ltmonitor.web.vo.VehicleModel;

@Controller
@RequestMapping("/vehicle")
public class VehicleAction extends PaginateAction {

	@Autowired
	private ITerminalService terminalService;

	@Autowired
	private IDepartmentService departmentService;

	@Autowired
	private IDriverInfoService driverInfoService;

	@Autowired
	private IRealDataService realDataService;

	@RequestMapping("/viewList.action")
	public String list() {
		return "/vehicle/vehicleList";
	}

	@RequestMapping("/view.action")
	public String view(
			Model m,
			@RequestParam(value = "entityId", required = false, defaultValue = "0") long vehicleId)
	{
		VehicleData vd = new VehicleData();
		if (vehicleId > 0) {
			vd = this.vehicleDataService.load(vehicleId);
		}

		Terminal terminal = null;
		if (vd.getTermId() > 0) {
			try {
				terminal = terminalService.load(vd.getTermId());
			} catch (Exception e) {
				log.error(e.getMessage(), e);
			}
		}

		DriverInfo vehicleDriver = null;
		if (vehicleId > 0) {
			vehicleDriver = this.driverInfoService.getMainDriverInfo(vehicleId);
		}
		if (vehicleDriver == null)
			vehicleDriver = new DriverInfo();
		if (terminal == null)
			terminal = new Terminal();
		m.addAttribute("entity", vd);
		m.addAttribute("saveAndNew", false);
		m.addAttribute("terminal", terminal);
		m.addAttribute("vehicleDriver", vehicleDriver);

		return "/vehicle/editVehicle";
	}//end view

	/**
	 * 假删除
	 * 
	 * @return
	 */
	@RequestMapping("/delete.action")
	@ResponseBody
	public JsonMessage fakeDelete(long entityId) {
		try {
			VehicleInfoModifyRecord vr = new VehicleInfoModifyRecord();
			vr.setVehicleId(entityId);
			vr.setType(VehicleInfoModifyRecord.MODIFY_DELETE);

			OnlineUser user = this.getOnlineUser();
			vr.setUserName(user.getName());
			vr.setDetail("删除车辆");
			vehicleDataService.delete(entityId, vr);
			return super.json(true, "记录已被成功刪除!");
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return json(false, e.getMessage());
		}
	}

	@RequestMapping("/viewInfo.action")
	public String viewVehicleInfo(long vehicleId, Model m) {
		try {

			Map params = new HashMap();
			// 单车监控，用于生成监控车辆轨迹
			params.put("vehicleId", vehicleId);
			String queryId = "selectVehicles"; // 查询单个车辆的综合信息
			List result = this.queryService.query(queryId, params);
			convert(result);
			Map vehicleInfo = null;
			if (result.size() > 0)
				vehicleInfo = (Map) result.get(0);
			else {
				vehicleInfo = new HashMap();
				m.addAttribute("message", "没有该车辆的信息数据");
			}
			m.addAttribute("vehicleInfo", vehicleInfo);
			// 还要加载驾驶员信息

			viewDriverInfo(vehicleId, 0, m);

		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			m.addAttribute("message", ex.getMessage());
		}
		return "/vehicle/viewVehicle";

	}

	/**
	 * 跳转到选择车辆的页面
	 * 
	 * @param m
	 * @return
	 */
	@RequestMapping("/selectVehicle.action")
	public String selectVehicle(Model m) {

		return "/vehicle/selectVehicle";
	}

	/**
	 * 获取终端信息
	 * 
	 * @param terminalId
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getTerminalInfo")
	public JsonMessage getTerminalInfo(long terminalId) {
		try {
			Terminal t = (Terminal) this.terminalService.load(terminalId);

			return json(true, t);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return json(false, e.getMessage());
		}
	}

	/**
	 * 查看驾驶员信息
	 * 
	 * @return
	 */
	@RequestMapping("/viewDriverInfo.action")
	public String viewDriverInfo(
			@RequestParam(defaultValue = "0") long vehicleId, long driverId,
			Model m) {
		Map driverInfo = new HashMap();
		try {
			if (vehicleId == 0 && driverId == 0) {
				driverInfo = new HashMap();
				m.addAttribute("message", "没有驾驶员信息数据");
			} else {

				Map params = new HashMap();
				// 单车监控，用于生成监控车辆轨迹
				if (vehicleId > 0) {
					params.put("vehicleId", vehicleId);
				}
				if (driverId > 0) {
					params.put("driverId", driverId);
				}

				String queryId = "driverInfo.selectDrivers"; // 查询单个车辆的综合信息
				List result = this.queryService.query(queryId, params);
				convertDriverInfo(result);
				if (result.size() > 0)
					driverInfo = (Map) result.get(0);
				else {
					driverInfo = new HashMap();
					m.addAttribute("message", "没有驾驶员信息数据");
				}

			}
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			m.addAttribute("message", ex.getMessage());
		}
		m.addAttribute("driverInfo", driverInfo);
		return "/driverInfo/viewDriverInfo";

	}

	private void convertDriverInfo(List ls) {
		for (Object rowData : ls) {
			Map rd = (Map) rowData;
			convert(rd, "sex", "Sex");// 性别转换
			convert(rd, "drivingType", "drivingType");// 驾驶车型
		}
	}

	private void convert(List ls) {
		for (Object rowData : ls) {
			Map rd = (Map) rowData;
			convert(rd, "runStatus", "runStatus");
			convert(rd, "useType", "UseType");
			convert(rd, "plateColor", "plateColor");
		}
	}

	@RequestMapping("/save.action")
	public String save(VehicleModel vm, Model m, boolean saveAndNew) {
		VehicleData entity = vm.getEntity();
		DriverInfo vehicleDriver = vm.getVehicleDriver();
		m.addAttribute("saveAndNew", saveAndNew);
		Terminal terminal = vm.getTerminal();
		if (entity.getDepId() == 0) {
			m.addAttribute("entity", entity);
			m.addAttribute("terminal", terminal);
			m.addAttribute("vehicleDriver", vehicleDriver);
			m.addAttribute("message", "请选择车组");
			return "/vehicle/editVehicle";
		}

		VehicleData vd = (VehicleData) entity;
		long vehicleId = vd.getEntityId();
		String oldSimNo = vd.getSimNo();
		List<VehicleInfoModifyRecord> modifyRecordList = new ArrayList<VehicleInfoModifyRecord>();
		if (vehicleId > 0) {
			OnlineUser user = this.getOnlineUser();
			VehicleData oldVd = this.vehicleDataService.load(vehicleId);
			oldSimNo = oldVd.getSimNo();
			if (oldVd.getPlateNo().equals(vd.getPlateNo()) == false
					|| oldVd.getPlateColor() != vd.getPlateColor()) {
				VehicleInfoModifyRecord vr = new VehicleInfoModifyRecord();
				vr.setVehicleId(vehicleId);
				vr.setType(VehicleInfoModifyRecord.MODIFY_PLATENO);
				vr.setUserName(user.getName());
				StringBuilder detail = new StringBuilder();
				if (oldVd.getPlateNo().equals(vd.getPlateNo()) == false) {
					detail.append("车牌号由[").append(oldVd.getPlateNo())
							.append("]变更为[").append(vd.getPlateNo())
							.append("]");
				}
				if (oldVd.getPlateColor() != vd.getPlateColor()) {
					String oldColorDescr = super.convert(
							"" + oldVd.getPlateColor(), "plateColor");
					String colorDescr = super.convert("" + vd.getPlateColor(),
							"plateColor");
					if (detail.length() > 0)
						detail.append(",");
					detail.append("车牌颜色由[").append(oldColorDescr)
							.append("]变更为[").append(colorDescr).append("]");
				}
				vr.setDetail(detail.toString());
				modifyRecordList.add(vr);
			}
			if (oldVd.getSimNo().equals(vd.getSimNo()) == false) {
				VehicleInfoModifyRecord vr = new VehicleInfoModifyRecord();
				vr.setVehicleId(vehicleId);
				vr.setType(VehicleInfoModifyRecord.MODIFY_SIMNO);
				vr.setUserName(user.getName());
				StringBuilder detail = new StringBuilder();
				detail.append("sim卡号由[").append(oldVd.getSimNo())
						.append("]变更为[").append(vd.getSimNo()).append("]");

				vr.setDetail(detail.toString());
				modifyRecordList.add(vr);
			}
			if (oldVd.getDepId() != vd.getDepId()) {
				VehicleInfoModifyRecord vr = new VehicleInfoModifyRecord();
				vr.setVehicleId(vehicleId);
				vr.setType(VehicleInfoModifyRecord.MODIFY_DEPARTMENT);
				vr.setUserName(user.getName());
				Department oldDep = this.departmentService
						.fetchDepartment(oldVd.getDepId());
				Department dep = this.departmentService.fetchDepartment(vd
						.getDepId());
				StringBuilder detail = new StringBuilder();
				detail.append("过户由[").append(oldDep.getName()).append("]变更为[")
						.append(dep.getName()).append("]");
				vr.setDetail(detail.toString());
				modifyRecordList.add(vr);
			}
			if (oldVd.getTermId() != vd.getTermId()) {
				if (oldVd.getTermId() > 0) {
					try {
						Terminal t = this.terminalService.load(oldVd
								.getTermId());
						t.setBind(false);
						this.terminalService.saveOrUpdate(t);
					} catch (Exception e) {
						log.error(e.getMessage(), e);
					}
				}
			}
		}
		try {
			Terminal t = null;
			if (vd.getTermId() > 0) {
				try {
					t = this.terminalService.load(vd.getTermId());
				} catch (Exception e) {
					log.error(e.getMessage(), e);
				}
			} else {
				t = new Terminal();
				t.setCompanyId(this.getOnlineUser().getCompanyId());
			}
			if (terminal != null) {
				String oldTermNo = t.getTermNo();
				t.setTermNo(terminal.getTermNo());
				t.setTermType(terminal.getTermType());
				t.setState(terminal.getState());
				t.setInstallTime(terminal.getInstallTime());
				t.setBind(true);
				t.setSimNo(vd.getSimNo());
				terminalService.saveOrUpdateTerminal(t);

				try {
					this.realDataService.updateTerminal(oldTermNo, t);
				} catch (Exception ex) {
					log.error(ex.getMessage(), ex);
				}
			}
			terminal = t;
			vd.setTermId(t.getEntityId());
			vd.setCompanyId(this.getOnlineUser().getCompanyId());
			vehicleDataService.saveVehicleData(vd, modifyRecordList);
			// entityID = "" + ((TenantEntity) entity).getEntityId();
			m.addAttribute("message", "保存成功!");
			vehicleId = vd.getEntityId();

			try {
				this.realDataService.updateVehicleData(oldSimNo, vd);
			} catch (Exception ex) {
				log.error(ex.getMessage(), ex);
			}
			try {
				if (vehicleDriver != null
						&& (vehicleDriver.getDriverName() != null
								|| vehicleDriver.getMobilePhone() != null || vehicleDriver
								.getMonitor() != null)) {
					DriverInfo d = null;
					if (vehicleId > 0) {
						d = this.driverInfoService.getMainDriverInfo(vehicleId);
					}

					if (d == null) {
						d = vehicleDriver;
						d.setMainDriver(true);
						d.setVehicleId(vehicleId);
						d.setCompanyId(this.getOnlineUser().getCompanyId());
					} else {
						d.setDriverName(vehicleDriver.getDriverName());
						d.setMobilePhone(vehicleDriver.getMobilePhone());
						d.setMonitor(vehicleDriver.getMonitor());
					}
					vehicleDriver = d;
					this.driverInfoService.saveOrUpdate(d);

				}
			} catch (Exception ex) {
				log.error(ex.getMessage(), ex);
				m.addAttribute("message", ex.getMessage());
			}
			
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			m.addAttribute("message", ex.getMessage());
		}

		
		m.addAttribute("entity", vd);
		m.addAttribute("terminal", terminal);
		m.addAttribute("vehicleDriver", vehicleDriver);
		return "/vehicle/editVehicle";

	}

}
